import React from 'react'
import { Table, Icon, Modal, Popconfirm, Form, Input, Row, Col, DatePicker, Button, Message,TreeSelect } from 'antd';
const FormItem = Form.Item;
import userApi from '../../../api/user';
import officeApi from '../../../api/office';
import roleApi from '../../../api/role';
const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import UserForm from '../../Form/User';
import { jsonToTree } from '../../../utils/tools'
import { setCommonProps } from '../../../actions/application'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { withRouter, matchPath } from 'react-router'

import '../../../style/antd-theme.less';

class TablePage extends React.Component {

  state = {
    data: [],
    pagination: {
      pageSize: 20,
      pageNum: 1,
    },
    loading: false,
    isOpenCreateUser: false,
    isOpenEditUser: false,
    offices: null,
    roles: null,
    user: null,
  };
  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
    this.fetch({
      ...pagination,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  }

  initData = () => {
    // 查看所有机构数据
    officeApi.get('/getAllOffice').then((data) => {
      const result = data.data;

      this.setState({
        offices: result,
      });
    });

    roleApi.get('/get').then((res) => {
      const result = res.data;
      for (let i = 0; i < result.length; i++) {
        result[i] = {
          value: result[i].id,
          label: result[i].name,
          key: result[i].id,
          parentId: result[i].parentId,
          id: result[i].id,
        }
      }

      this.setState({
        roles: jsonToTree({
          json: result,
          keepChild: false
        }),
      });
    });
  }

  fetch = (params) => {
    this.setState({ loading: true });
    userApi.get('/getAllUser', { params }).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () => {
    this.fetch({ ...this.state.pagination });
    this.props.setCommonProps('wudi','wudi hehe!!');
    
    this.initData();
  }

  startCreateUser = () => {
    if (this.resetFields) this.resetFields();
    if (this.clearPho) this.clearPho();
    this.setState({
      isOpenCreateUser: true,
      user: null,
      clearForm: false,
    });
  }

  startUpdateUser = (record) => {
    if (this.resetFields) this.resetFields();
    if (this.clearPho) this.clearPho();
    // 根据用户ID用户用户角色信息
    userApi.get('/queryUserRolesByUserId', {
      id: record.id
    }).then((res) => {
      const data = res.data;

      if (data) {
        let userRoles = [];
        for (let i = 0; i < data.length; i++) {
          userRoles.push({
            value: data[i].id,
            label: data[i].label,
          });
        }
        record.userRoles = userRoles;
      }
      this.setState({
        user: record,
        isOpenEditUser: true,
        clearForm: false,
      });
    });
  }

  close = () => {
    this.setState({
      isOpenEditUser: false,
      isOpenCreateUser: false,
      clearForm: true,
    });
  }

  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }


  handleLogOut = () => {
    const { logout } = this.props
    logout().payload.promise.then(() => {
      this.props.history.replace('/login');
    });
  }

  deleteAll = () => {
    const ids = this.state.delIds;
    if (ids == '' || ids == null) {
      Message.error('请选择你要删除的用户！');
      return;
    }
    this.deleteUser(ids);
  }

  delete = (id, event) => {
    this.deleteUser(id);
  }

  deleteUser = (ids) => {
    userApi.delete('/delUser', { ids: ids }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('删除成功！');
        this.fetch();
      } else {
        Message.error(result.message);
      }
    });
  }

  resetPassword = (id, event) => {
    userApi.put('/resetPassword', { id: id }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('重置成功！');
        this.fetch();
      } else {
        Message.error(result.message);
      }
    });
  }

  // 接收子组件传入的数据及其方法
  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
    this.clearPho = params.clearPho;
  }
   columns = [{
    title: '姓名',
    dataIndex: 'name',
    width: '15%',
  }, {
    title: '登录名',
    dataIndex: 'loginName',
    width: '15%',
  }, {
    title: '注册时间',
    dataIndex: 'create_date',
    width: '18%',
    sorter: true,
  }, {
    title: '手机号码',
    dataIndex: 'phone',
    width: '13%',
  }, {
    title: '用户类型',
    dataIndex: 'type',
    width: '13%',
    render: (text, record, index) => {
      switch (record.userType) {
        case '1':
          return '系统用户';
        case '2':
          return '微信用户';
        case '3':
          return '平台用户';
        default:
          return '未知';
      }
    },
  }, {
    title: '操作',
    key: 'action',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.startUpdateUser.bind(this, record)} >编辑</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要重置该用户的密码?" onConfirm={this.resetPassword.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">重置密码</a>
        </Popconfirm>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该用户?" onConfirm={this.delete.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    }
  };

  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};

    return (
      <div>
        <SearchUserForm searchUserState={this.state} goSearch={this.handleTableChange} deleteAll={this.deleteAll} startCreateUser={this.startCreateUser} offices={this.state.offices} />
        <PanelBox>
          <Table columns={this.columns} rowKey={record => record.registered} dataSource={this.state.data} pagination={this.state.pagination}
            loading={this.state.loading} onChange={this.handleTableChange} rowSelection={this.rowSelection} rowKey={'id'}
            expandedRowRender={record => <p style={{ margin: 0 }}>工号:{record.no}　　　手机号码:{record.phone}　　　注册时间:{record.create_date}</p>}
          />
        </PanelBox>
        <Modal
          title="创建用户"
          visible={this.state.isOpenCreateUser}
          onOk={this.close}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="1000"
          footer={null}
        >
          <UserForm user={this.state.user} clearForm={this.state.clearForm} refeshData={this.refeshData} offices={this.state.offices} roles={this.state.roles} close={this.close} callbackParent={this.initChildrenParams} />
        </Modal>
        <Modal
          title="修改用户"
          visible={this.state.isOpenEditUser}
          onOk={this.close}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="1000"
          footer={null}
        >
          <UserForm user={this.state.user} clearForm={this.state.clearForm} refeshData={this.refeshData} offices={this.state.offices} roles={this.state.roles} close={this.close} callbackParent={this.initChildrenParams} />
        </Modal>
      </div>
    );
  }
}

class SearchForm extends React.Component {
  // 开始搜索
  goSearch = (e) => {
    let params = this.props.form.getFieldsValue().search;
    let _this = this.props;
    params.pageSize = _this.searchUserState.pagination.pageSize;
    params.pageNum =1;
    params.current =1;
    if (params.date.length > 0) {
      params.startCreateDate = moment(params.date[0]).format("YYYY-MM-DD");
      params.endCreateDate = moment(params.date[1]).format("YYYY-MM-DD");
    }
    delete params.date;
    _this.goSearch(params,{},{});

  }
  deleteAll = (e) => {
    this.props.deleteAll();
  }



  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = this.srearchStyle;

    return <Form onSubmit={this.goSearch} layout="inline" style={{ marginBottom: '10px' }}>
      <FormItem {...formItemLayout} label="机构" style={{ marginBottom:10}}>
        {getFieldDecorator('search.officeId', {
        })(
          <TreeSelect
          style={{width:250}}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={this.props.searchUserState.offices}
            placeholder="请选择所属机构"
            treeDefaultExpandAll
          />
          )}
      </FormItem>
      <FormItem {...formItemLayout} label="姓名" >
        {getFieldDecorator('search.name', {
        })(
          <Input type="text" placeholder="请输入姓名" />
          )}
      </FormItem>
      <FormItem {...formItemLayout} label="登陆名" >
        {getFieldDecorator('search.loginName', {
        })(
          <Input type="text" placeholder="请输入登录名" />
          )}
      </FormItem>
      <FormItem {...formItemLayout} label="注册日期" >
        {getFieldDecorator('search.date', {
          initialValue: []
        })(
          <RangePicker format="YYYY/MM/DD" />
          )}
      </FormItem>
      <FormItem >
        <Button type="primary" icon="search" htmlType="submit">搜索</Button>
      </FormItem>
      <FormItem>
        <Popconfirm type="primary" icon="minus" title="您是否要删除选中的所有用户?" onConfirm={this.deleteAll} okText="是" cancelText="否">
          <Button type="primary" icon="minus" style={{ height: 32 }}>删除所选</Button>
        </Popconfirm>
      </FormItem>
      <FormItem>
        <Button type="primary" icon="plus" onClick={this.props.startCreateUser}>新建用户</Button>
      </FormItem>
    </Form>
  }
}
const SearchUserForm = Form.create({})(SearchForm);

function mapStateToProps(state) {
  return {
    wudi:state.application.wudi
  }
}

function mapDispatchToProps(dispatch) {
  return {
    setCommonProps: bindActionCreators(setCommonProps, dispatch),
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TablePage))